package cn.fufeiii.bt.common.aspect.lock;

import org.redisson.RedissonMultiLock;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * Redisson
 *
 * @author FuFei
 */
@Component
@ConditionalOnBean(RedissonClient.class)
public class RedissonLockHelper {
    @Autowired
    private RedissonClient redissonClient;

    /**
     * 是否被锁住
     *
     * @param key *
     * @return *
     */
    public boolean isLocked(String key) {
        return this.getLock(key).isLocked();
    }

    /**
     * 获取分布式锁
     *
     * @param key *
     * @return *
     */
    public RLock getLock(String key) {
        // 返回是RedissonLock
        return redissonClient.getLock(key);
    }

    /**
     * 是否被锁住
     *
     * @param keyList *
     * @return *
     */
    public boolean isLocked(List<String> keyList) {
        return this.getLock(keyList).isLocked();
    }

    /**
     * 获取分布式锁
     *
     * @param keyList *
     * @return *
     */
    public RLock getLock(List<String> keyList) {
        List<RLock> rLockList = new ArrayList<>(keyList.size());
        for (String key : keyList) {
            rLockList.add(this.getLock(key));
        }
        return new RedissonMultiLock(rLockList.toArray(new RLock[0]));
    }

}
